#pragma once

#include <sys/ipc.h>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <string>
#include <cstring>
#include <cerrno>
#include <cstdlib>
#include <fcntl.h>
#include <unistd.h>
#include <sys/shm.h>

using namespace std;

const string pathname = "/home/pxt/109/linux/test_9_21";
const int proj_id = 0x11223344;
const string FileName = "fifo";

const int size = 4096;

key_t GetKey()
{
    key_t key = ftok(pathname.c_str(), proj_id);
    if(key < 0)
    {
        cerr << "errno: " << errno << ", strerrno: " << strerror(errno) << endl;
        exit(1);
    }

    return key;
}

string ToHex(int id)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", id);
    return buffer;
}

int CreateShmHelper(key_t key, int flag)
{
    int shmid = shmget(key, size, flag);  

    if(shmid < 0)
    {
        cerr << "errno: " << errno << ", strerrno: " << strerror(errno) << endl;
        exit(1);
    }
    return shmid;
}

int CreateShm(key_t key)
{
    return CreateShmHelper(key, IPC_CREAT|IPC_EXCL|0644);
}

int GetShm(key_t key)
{
    return CreateShmHelper(key, IPC_CREAT);
}

bool MakeFifo()
{
    int n = mkfifo(FileName.c_str(), 0666);
    if(n < 0)
    {
        cerr << "errno: " << errno << ", strerrno: " << strerror(errno) << endl;
        return false;
    }

    cout << "mkfifo success ... ... read" << endl;
    return true;
}